package cc.avatar.repository;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cc.avatar.model.SaleState;
import cc.avatar.model.dao.ProductDao;

public class TrackingNumberCounter {

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");

    public String createSaleTrackingNumber(){
    	return createNextTrackingNumber("S");
    }
    
    public String createWarehousingTrackingNumber(){
    	return createNextTrackingNumber("P");
    }
    
	//S - Sale, I - Warehousing
	@SuppressWarnings("unchecked")
	private String createNextTrackingNumber(String type) {
		String today = DATE_FORMAT.format(new Date());
		String clzName = "S".equalsIgnoreCase(type)? "Sale":"Warehousing";
		// recount from database
		String hql = "select count(*) from " + clzName;
		List results = null;
		if ("S".equals(type)){
			hql = hql + " where state != ?";
			results = dao.getHibernateTemplate().find(hql, SaleState.draft);
		}else		
		    results = dao.getHibernateTemplate().find(hql);
		int max = results.get(0) != null ? ((Long) results.get(0)).intValue():0;
		StringBuffer sn = new StringBuffer();
		max++;
		sn.append(type).append(today).append("-").append(max);
		return sn.toString();
	}
	
	private ProductDao dao;
	
	public void setDao(ProductDao dao){
		this.dao = dao;
	}
}
